class EspIdf < Formula
  desc "Espressif IoT Development Framework"
  homepage "https://github.com/espressif/esp-idf"
  url "https://github.com/espressif/esp-idf.git",
      tag: "v5.4",  # 替换为你需要的版本号
      revision: "d5c5d1c6a8f1b2e3c4d5e6f7a8b9c0d1e2f3a4b5"  # 替换为实际提交哈希
  license "Apache-2.0"
  head "https://github.com/espressif/esp-idf.git", branch: "master"

  # 定义 ESP-IDF 依赖的 Python 包
  resource "idf-python-requirements" do
    url "https://raw.githubusercontent.com/espressif/esp-idf/#{version}/requirements.txt"
    sha256 "..."  # 替换为实际 SHA-256
  end

  # ESP-IDF 的依赖项
  depends_on "cmake"
  depends_on "ninja"
  depends_on "ccache"
  depends_on "dfu-util"
  depends_on "libusb"
  depends_on "python@3.11"

  # ESP-IDF 还需要以下工具
  depends_on "xtensa-esp32-elf" => :optional
  depends_on "xtensa-esp32s2-elf" => :optional
  depends_on "xtensa-esp32s3-elf" => :optional
  depends_on "riscv32-esp-elf" => :optional
  depends_on "esp32ulp-elf" => :optional
  depends_on "openocd-esp32" => :optional

  def install
    # 创建环境变量设置脚本
    (bin/"export-esp-idf.sh").write <<~EOS
      #!/bin/bash
      export IDF_PATH="#{prefix}"
      export IDF_TOOLS_PATH="${IDF_TOOLS_PATH:-$HOME/.espressif}"
      source "#{prefix}/export.sh"
    EOS
    chmod 0755, bin/"export-esp-idf.sh"

    # 安装 Python 依赖
    venv = virtualenv_create(libexec, "python3.11")
    resource("idf-python-requirements").stage do
      venv.pip_install Pathname.pwd/"requirements.txt"
    end

    # 复制 export.sh 脚本
    cp "export.sh", prefix

    # 创建工具安装脚本
    (bin/"install-esp-idf-tools").write <<~EOS
      #!/bin/bash
      source "#{bin}/export-esp-idf.sh"
      python "#{prefix}/tools/idf_tools.py" install all
    EOS
    chmod 0755, bin/"install-esp-idf-tools"
  end

  def caveats; <<~EOS
    要使用 ESP-IDF，请配置环境变量：
      source #{opt_bin}/export-esp-idf.sh

    安装所需的工具链：
      install-esp-idf-tools

    这将安装所有必要的工具链和工具到 ~/.espressif 目录。

    首次使用建议运行：
      idf.py set-target esp32
      idf.py build
    EOS
  end

  test do
    ENV["IDF_PATH"] = prefix
    system "#{bin}/export-esp-idf.sh"
    assert_match "ESP-IDF", shell_output("idf.py --version", 1)
  end
end